package com.tanxi521.afkreward.util;

import com.tanxi521.afkreward.AfkReward;
import com.tanxi521.afkreward.data.AFKRewardMapper;
import com.tanxi521.afkreward.pojo.Area;
import com.tanxi521.afkreward.pojo.PlayerAfk;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class CommandUtil {

    public static boolean freeAfkList(CommandSender sender) {
        for (int i = 0; i <= 30; i++) sender.sendMessage("");
        sender.sendMessage("§e点击下方类型开始挂机");
        List<String> keys = ConfigUtil.getAllType();
        for (String key : keys) {
            TextComponent tc = new TextComponent("- " + key);
            ClickEvent ce = new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tna start " + key);
            HoverEvent he = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new BaseComponent[]{new TextComponent(ConfigUtil.getTypeDes(key))});
            tc.setHoverEvent(he);
            tc.setClickEvent(ce);
            sender.spigot().sendMessage(tc);
        }
        return true;
    }

    public static boolean startFreeAfk(CommandSender sender, String afkName) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(ColorUtil.replace("&c&l控制台挂什么机?"));
            return false;
        }
        if (!sender.hasPermission("AfkRewards.start." + afkName)) {
            sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("nopermission")));
            return false;
        }
        if (!ConfigUtil.getEnableFree()) {
            sender.sendMessage(ColorUtil.replace("&c&l自由挂机当前处于关闭状态!"));
            return false;
        }
        if (!AFKRewardMapper.isAfk(sender.getName())) {
            sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("started")));
            return false;
        }
        if (!ConfigUtil.getAllType().contains(afkName)) {
            sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("nosuchtype")));
            return false;
        }
        if (ConfigUtil.isPlayerLimit() && AFKRewardMapper.AFK_MAP.size() >= ConfigUtil.getMaxNum() && !sender.hasPermission("AfkRewards.not.player.limit")) {
            sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("startmax")));
            return false;
        }
        PlayerAfk playerAfk = AFKRewardMapper.getPlayerInfo(sender.getName());
        if (playerAfk != null) {
            playerAfk.setType("自由");
            playerAfk.setReward(afkName);
            playerAfk.setStart(System.currentTimeMillis());
            playerAfk.setEnd(0L);
            AFKRewardMapper.startAfk(playerAfk);
            AFKRewardMapper.AFK_MAP.put(sender.getName(), playerAfk);
            sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("startafk")).replace("%player%", sender.getName()));
        } else {
            sender.sendMessage("§e开始挂机失败，请联系管理员或重新进入服务器尝试");
        }
        return true;
    }

    public static boolean stopAfk(CommandSender sender) {
        if (AFKRewardMapper.isAfk(sender.getName())) {
            sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("notstart")));
            return false;
        }
        PlayerAfk playerInfo = AFKRewardMapper.getPlayerInfo(sender.getName());
        if (playerInfo == null || playerInfo.getPlayerName() == null) {
            sender.sendMessage("§e系统错误，玩家不存在，请联系管理员");
            return false;
        }
        boolean isOffLineFlag = true;
        if (playerInfo.getEnd() == 0) {
            playerInfo.setEnd(System.currentTimeMillis());
            isOffLineFlag = false;
        }
        long count = RewardUtil.giveRewards(playerInfo, sender);
        if (isOffLineFlag) sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("offonlinemsg")));
        AfkReward.getInstance().getServer().broadcastMessage(ColorUtil.replace(ConfigUtil.langYml.getString("rewardsmsg"))
                .replace("%player%", playerInfo.getPlayerName())
                .replace("%afktime%", RewardUtil.time(playerInfo.getEnd() - playerInfo.getStart())).replace("%times%", count + ""));
        return true;
    }

    public static boolean startAreaAfk(CommandSender sender) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(ColorUtil.replace("&c&l控制台挂什么机?"));
            return false;
        }
        if (!ConfigUtil.getEnableArea()) {
            sender.sendMessage(ColorUtil.replace("&c&l区域挂机当前处于关闭状态!"));
            return false;
        }
        if (!AFKRewardMapper.isAfk(sender.getName())) {
            sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("started")));
            return false;
        }
        if (ConfigUtil.isPlayerLimit() && AFKRewardMapper.AFK_MAP.size() >= ConfigUtil.getMaxNum()) {
            sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("startmax")));
            return false;
        }
        double x = ((Player) sender).getPlayer().getLocation().getX();
        double z = ((Player) sender).getPlayer().getLocation().getZ();
        MapPoint mapPoint = new MapPoint();
        mapPoint.setLng(x);
        mapPoint.setLat(z);
        String worldName = ((Player) sender).getLocation().getWorld().getName();
        List<Area> areas = ConfigUtil.areas.stream().filter(a -> a.getWorld().equals(worldName)).collect(Collectors.toList());
        if (areas.size() <= 0) {
            sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("noneworld")));
            return false;
        }
        boolean findArea = true;
        for (Area area : areas) {
            if (GraphUtils.isPointInPolygon(mapPoint, area.getMapPoints())) {
                if (!AfkReward.getInstance().getConfig().getBoolean("area." + area.getName() + ".enable")) {
                    sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("unableArea")));
                    return false;
                }
                if (!sender.hasPermission("AfkRewards.area." + area.getName())) {
                    sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("nopermission")));
                    return false;
                }
                PlayerAfk playerAfk = new PlayerAfk();
                playerAfk.setPlayerName(sender.getName());
                playerAfk.setType("区域");
                playerAfk.setReward(area.getName());
                playerAfk.setStart(System.currentTimeMillis());
                playerAfk.setEnd(0L);
                AFKRewardMapper.startAfk(playerAfk);
                AFKRewardMapper.AFK_MAP.put(sender.getName(), playerAfk);
                findArea = false;
                break;
            }
        }
        if (findArea) {
            sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("nonearea")));
            return false;
        }
        sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("startArea")));
        return true;
    }

    public static boolean afkList(int currentPage, CommandSender sender) {
        int perPage = 10;
        List<PlayerAfk> afkList = AFKRewardMapper.getAfkPlayerList(currentPage == 1 ? 0 : (currentPage - 1) * perPage, perPage);
        int count = AFKRewardMapper.getAfkCount();
        int totalPage = count % perPage == 0 ? count / perPage : count / perPage + 1;
        for (int i = 0; i < 30; i++) sender.sendMessage("");
        sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("afklisttitle")));
        int i = currentPage == 1 ? currentPage : (currentPage - 1) * perPage + 1;
        if (afkList != null) {
            for (PlayerAfk playerAfk : afkList) {
                ArrayList<BaseComponent> bc = new ArrayList<>();
                String status = playerAfk.getType().equals("自由") ? "§2自由挂机" : "§b区域挂机";
                String reward = playerAfk.getType().equals("自由") ? "§6类型" : "§6区域";
                TextComponent tc1 = new TextComponent("§6No. " + i + " §b玩家: " + playerAfk.getPlayerName() + " §6状态: " +
                        status + " " + reward + ": §b" + playerAfk.getReward() + " §6当前挂机时间: " + RewardUtil.afkTime(playerAfk));
                bc.add(tc1);
                BaseComponent[] bcR = new BaseComponent[bc.size()];
                bc.toArray(bcR);
                sender.spigot().sendMessage(bcR);
                i++;
            }
        }
        page(currentPage, totalPage, count, sender, "list");
        return true;
    }

    public static boolean top(CommandSender sender, int currentPage) {
        int perPage = 10;
        List<PlayerAfk> afkList = AFKRewardMapper.getAfkTop(currentPage == 1 ? 0 : (currentPage - 1) * perPage, perPage);
        int count = AFKRewardMapper.getAllCount();
        int totalPage = count % perPage == 0 ? count / perPage : count / perPage + 1;
        for (int i = 0; i < 30; i++) sender.sendMessage("");
        sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("afkranktitle")));
        int i = currentPage == 1 ? currentPage : (currentPage - 1) * perPage + 1;
        if (afkList != null) {
            for (PlayerAfk playerAfk : afkList) {
                ArrayList<BaseComponent> bc = new ArrayList<>();
                TextComponent tc1 = new TextComponent("§6No. " + i + " §b玩家: " + playerAfk.getPlayerName() + " §6挂机总时间: " +
                        RewardUtil.time(playerAfk.getTotal()) + " §6获得奖励次数: §a" + playerAfk.getTimes());
                bc.add(tc1);
                BaseComponent[] bcR = new BaseComponent[bc.size()];
                bc.toArray(bcR);
                sender.spigot().sendMessage(bcR);
                i++;
            }
        }
        page(currentPage, totalPage, count, sender, "top");
        return true;
    }

    public static void page(int currentPage, int totalPage, int count, CommandSender sender, String pageName) {
        sender.sendMessage("");
        ArrayList<BaseComponent> bc = new ArrayList<>();
        TextComponent tc1 = new TextComponent("§2点击上一页");
        ClickEvent ce1 = new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tna " + pageName + " " + (currentPage <= 1 ? 1 : currentPage - 1));
        HoverEvent he1 = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new BaseComponent[]{new TextComponent("§e点击查看第" + (currentPage <= 1 ? 1 : currentPage - 1) + "页")});
        tc1.setClickEvent(ce1);
        tc1.setHoverEvent(he1);
        bc.add(tc1);
        TextComponent tc3 = new TextComponent("§a  当前为第 " + currentPage + " 页,共 " + totalPage + " 页,总共 " + count + " 名玩家  ");
        bc.add(tc3);
        TextComponent tc2 = new TextComponent("§2点击下一页");
        ClickEvent ce2 = new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tna " + pageName + " " + (currentPage >= totalPage ? totalPage : currentPage + 1));
        HoverEvent he2 = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new BaseComponent[]{new TextComponent("§e点击查看第" + (currentPage >= totalPage ? totalPage : currentPage + 1) + "页")});
        tc2.setClickEvent(ce2);
        tc2.setHoverEvent(he2);
        bc.add(tc2);
        BaseComponent[] bcR = new BaseComponent[bc.size()];
        bc.toArray(bcR);
        sender.spigot().sendMessage(bcR);
    }

    public static boolean reload(CommandSender sender) {
        if (!sender.isOp()) {
            sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("reloadnopermission")));
            return false;
        }
        AfkReward.getInstance().reloadConfig();
        ConfigUtil.langYml = null;
        ConfigUtil.areas = new LinkedList<>();
        ConfigUtil.initMsg();
        ConfigUtil.initArea();
        sender.sendMessage(ColorUtil.replace(ConfigUtil.langYml.getString("reload")));
        return true;
    }
}
